// 存储用户点赞文章的列表, 实现全局likes的添加, local上的存储, 方便当前会话的内容获取
/*
  全局管理user的数据
  1. state: 
    token(设置token, 随时访问, 判断token是否存在, 存在就直接登录)
    userInfo(用户登录后的信息, 存储)
  2. mutations:
    设置token, 修改userInfo
  3. actions:
    在用户登录后, 将token设置到 state.token, 设置直接根据token, 请求user

*/
import { defineStore } from 'pinia'
import store from 'store'

import $http from '@/api/http'
import base from '@/config/base.config'

const { LISTEN_LIKE } = base
export const useLike = defineStore('like', {
  state: () => {
    return {
      likeList: store.get(LISTEN_LIKE) || [],
    }
  },
  actions: {
    isLike(aid) {
      return this.likeList?.includes(aid)
    },
    // 给likeList修改文章id
    changeLikeList() {
      this.likeList = store.get(LISTEN_LIKE) || []
    },
    // 添加文章id到likeList
    pushLike(payload) {
      let { aid } = payload
      // state.likeList添加aid 为了实现数据统一, 避免刷新后vuex重置 从local中获取文章List
      let likeList = store.get(LISTEN_LIKE) || []
      if (aid && !likeList.includes(aid)) {
        likeList.push(aid)
      }
      store.set(LISTEN_LIKE, likeList)
      this.likeList = store.get(LISTEN_LIKE) || []
    },
    // 删除文章中id
    pullLike(payload) {
      let { aid } = payload
      let likeList = store.get(LISTEN_LIKE) || []
      let index = likeList.indexOf(aid)
      if (aid && index !== -1) {
        likeList.splice(index, 1)
      }
      store.set(LISTEN_LIKE, likeList)
      this.likeList = store.get(LISTEN_LIKE) || []
    },
    async sendHttpLike({ aid }) {
      try {
        await $http({ type: 'postArticleLike', data: { id: aid } })
      } catch (err) {
        console.log(err)
      }
    },
  },
})
